package com.bw.lib_common.mvi

import android.os.Bundle
import android.os.PersistableBundle
import android.text.TextUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseActivity<VDB: ViewDataBinding,VM:BaseViewModel<*>>:AppCompatActivity() {
    lateinit var vm: VM
    lateinit var binding: VDB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this,getLayoutId())
        vm = ViewModelProvider(this)[getViewModelClass()]
        initView()

        lifecycleScope.launch {
            vm.state.collect {
                when(it){
                    is UIState.Loading -> {

                    }
                    is UIState.Success<*> -> {
                        observerData(it as UIState.Success<VM?>)
                    }
                    is UIState.Error -> {
                        Log.e("err", "onCreate: ${it.msg}", )
                    }
                }
            }
        }

        //初始EventBus
        EventBus.getDefault().register(this)
    }

    abstract fun getViewModelClass(): Class<VM>

    abstract fun getLayoutId(): Int

    abstract fun observerData(it: UIState.Success<VM?>)

    abstract fun initView()

    override fun onDestroy() {
        super.onDestroy()
        //反注册EventBus
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onReceive(event: CustomEvent?) {
        //校验一下目标页面
        if (null != event && !TextUtils.isEmpty(event.target)
            && event.target == javaClass.simpleName
        ) {
            handEvent(event)
        }
    }

    protected open fun handEvent(event: CustomEvent?) {
        //让其在子类中实现
    }
}